<template>
  <td v-if="defData && defData.def" :class="isSelected?'cellSelected':'cell'" @click="onCellClick" @dblclick="onDblclick" >
    <template v-if="defData.def.type === 'text'">
      <div style="width: 100%;height: 100%;background-color: #F2F8FF;" class="textCenter">{{ defData.value }}</div>
    </template>
    <template v-else-if="defData.def.type === 'input'">
      <template v-if="status === 'view'">{{ data.value }}</template>      
      <input ref="inputControl" v-else v-model="data.value" type="text" @focusout="status = 'view'" class="inputControl" />      
    </template>
    <select v-else-if="defData.def.type === 'select'" class="textCenter selectControl" style="width: 100%;height: 100%;" v-model="data.value" :disabled ="readonly">
        <option v-for="option in defData.def.options" :key="option.value" :value="option.value">
          {{ option.label }}
        </option>
    </select>
  </td>
</template>

<script>
export default {
  props: {
    defData:{
      type: Object,
      default:()=>{return {}}
    },
    rowIndex:{
      type: Number,
      default: undefined
    },
    columnIndex:{
      type: Number,
      default: undefined
    },
    readonly:{
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      data: this.defData,
      status: 'view',
      isSelected: false,
    };
  },
  methods: {
    onDblclick() {
      console.log('onDblclick:',this.readonly)
      if(!this.readonly && this.defData.def.type === 'input'){
        this.status = 'edit';
        this.$nextTick(() => {
          this.$refs.inputControl.focus();
        })
      }
    },
    onCellClick(){
        this.$emit('cell-click',this);
        this.isSelected = true
    }
  }
}
</script>

<style scoped>
.cellSelected{
  outline: black 2px solid;
}
.textCenter{
  display: flex; 
  justify-content: center;
  align-items: center;
  text-align: center;
}
.inputControl{
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  border: none;
}
.selectControl{
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  border: none;
}
.selectControl:active{
  border: none;
}
</style>